<template>
  <div class="details">
    <el-card>
      <el-tabs>
        <el-tab-pane lazy label="登录账户设置">
          <el-form
            ref="form"
            :model="form"
            :rules="rules"
            label-width="100px"
            style="margin: 20px auto; width: 500px"
          >
            <el-form-item label="姓名" prop="username">
              <el-input v-model="form.username" />
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input v-model="form.password" type="password" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submit">更新</el-button>
              <el-button @click="$router.back()">取消</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane lazy label="个人详情">
          <component
            :is="'userInfo'"
            :user-info="initUserInfo"
            @input="changeName"
          />
        </el-tab-pane>
        <el-tab-pane lazy label="岗位信息">
                <component
            :is="'jobInfo'"
          />
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script>
import { sysUser } from '@/api/user'
import { saveUserInfo } from '@/api/employees'
export default {
  components: {
    userInfo: () => import('./components/userInfo.vue'),
    jobInfo: () => import('./components/jobInfo.vue')
  },
  data() {
    return {
      userId: this.$route.params.id,
      userInfo: {},
      initUserInfo: {},
      form: {
        username: '',
        password: ''
      },
      rules: {
        username: [
          { required: true, message: '必填', trigger: 'blur' },
          { min: 1, max: 6, message: '请输入5~12个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '必填', trigger: 'blur' },
          { min: 5, max: 12, message: '请输入5~12个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getData()
  },
  methods: {
    async getData() {
      const res = await sysUser(this.userId)
      //   console.log(res)
      this.form.username = res.data.username
      this.userInfo = res.data
      // 深拷贝用户数据,传给员工详情页
      this.initUserInfo = JSON.parse(JSON.stringify(res.data))
    },

    submit() {
      this.$refs.form.validate(async(result) => {
        if (result) {
          //   console.log('验证成功')
          // 更新需要所有用户信息字段
          await saveUserInfo(Object.assign({}, this.userInfo, this.form))
          // 同步两个页面姓名数据
          this.initUserInfo.username = this.form.username
          this.$message.success('更新账户信息成功!')
        } else {
          console.log('验证失败')
        }
      })
    },
    // 同步两个页面姓名数据
    changeName(str) {
      this.form.username = str
    }
  }
}
</script>

<style></style>
